# -*- coding: utf-8 -*-
"""
Created on 2015年10月10日下午3:01:18

@author: 李鹏飞
定点任务,重启,还在; 过期后重启,不执行,直接删除;
"""
import logging

from apscheduler.events import EVENT_JOB_ERROR
from apscheduler.events import EVENT_JOB_EXECUTED
from apscheduler.executors.pool import ProcessPoolExecutor
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.background import BackgroundScheduler

# from auction.apps.advert.models import Advert

logger = logging.getLogger(__name__)


def myfunc():
    # 改存数据库
    # a=int('as')
    logger.info('aps测试22222[%s]' % 'aaa')
    # Advert.objects.create(image='11112222', link='2222222222')


jobstores = {
    # 'mongo': MongoDBJobStore(),
    # 'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
    'default': SQLAlchemyJobStore(url='mysql://root:123456@localhost:3306/auction?charset=utf8')
    # mysql://username:password@server/db
    # 'mysql://root:root@localhost:5379/sqlalchemy_tutorial?charset=utf8'
}
executors = {
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 3
}

scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
# scheduler = BackgroundScheduler()
# scheduler = BlockingScheduler()
# j = scheduler.add_job(myfunc, 'interval', minutes=1, id='my_job_id8')
# print job
# j=scheduler.add_job(myfunc,'cron', second='*/3', hour='*')
# j=scheduler.add_job(myfunc, 'cron', args=['cccc'], hour=3, id="backup_database", replace_existing=True)

# jobs = scheduler.get_jobs(jobstore=jobstores['default'])
# print jobs
# for job in jobs:
#     print job.id
#     print job.next_run_time
#     print job.func

scheduler.start()


# job = scheduler.get_job('my_job_id8')

# job.modify(next_run_time='')

# scheduler.remove_job('my_job_id')
def my_listener(event):
    logger.info(event.scheduled_run_time)
    logger.info(event.retval)
    logger.info(event.code)
    logger.info(event.job_id)
    if event.exception:
        logger.info(event.exception)
        logger.info('The job crashed :(')
    else:
        logger.info('The job worked :)')


scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
j = scheduler.add_job(myfunc, 'cron', hour=2, id="backup_database_2am", replace_existing=True)
print j
# try:
#     run_time = datetime.datetime.now() + datetime.timedelta(minutes=1)
#     job = scheduler.add_job(myfunc, 'date', args=['qqq'], id='qweqwe', run_date=run_time, replace_existing=True)
#     print job
# except Exception as e:
#     print e
